package com.cup.common.encryption;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
public class Base64Utils {

    public static String base64Encode(byte[] b) {
		Base64 base64 = new Base64();
		String base64Str = new String(base64.encode(b));
		String safeBase64Str = base64Str.replace('+', '-');
		safeBase64Str = safeBase64Str.replace('/', '_');
		safeBase64Str = safeBase64Str.replaceAll("=", "");

		return safeBase64Str;
	}

	public static byte[] base64Decode(String safeBase64Str) {
		String base64Str = safeBase64Str.replace('-', '+');
		base64Str = base64Str.replace('_', '/');
		int mod4 = base64Str.length() % 4;
		if (mod4 > 0) {
			base64Str = base64Str + "====".substring(mod4);
		}

		Base64 base64 = new Base64();
		return base64.decode(base64Str.getBytes());
	}

  /**
   * BASE64Encoder 加密
   * @param data 要加密的数据
   * @return 加密后的字符串
   */
  public static String encryptBASE64(byte[] data) {
      BASE64Encoder encoder = new BASE64Encoder();
      String encode = encoder.encode(data);
      return encode;
  }

  /**
   * BASE64Decoder 解密
   * @param data 要解密的字符串
   * @return 解密后的byte[]
   * @throws Exception
   */
  public static byte[] decryptBASE64(String data) throws Exception {
      BASE64Decoder decoder = new BASE64Decoder();
      byte[] buffer = decoder.decodeBuffer(data);
      return buffer;
  }
}
